import * as React from 'react'
import { Form, Input, Button, message } from 'antd'
import { useHistory } from 'react-router-dom'
import { FormInstance } from 'antd/lib/form'
import style from './style.module.css'
import * as api from '../../services/api'

interface Values {
  username: string
  password: string
}

export default function Login() {
  let formRef: FormInstance<Values> | null
  const history = useHistory()
  const submit = async () => {
    try {
      const value = await formRef?.validateFields()
      const lenN = String(value?.username).length
      const lenP = String(value?.password).length
      if (lenN < 6 || lenN > 11 || lenP < 6 || lenP > 8) {
        message.error('请保证你输入用户名的长度是6-11，密码长度6-8!')
        return
      }
      const result = await api.login(value?.username, value?.password)
      if (result.stat === 'OK') {
        message.success('登录成功')
        history.push('/home')
      } else {
        message.error(result.message)
      }
    } catch (error) {
      console.trace(error)
    }
  }

  return (
    <div className={style.wrap}>
      <Form className={style.form} ref={(e) => formRef = e} initialValues={{ "username": '', "password": '' }}>
        <div className={style.title}>登录</div>
        <Form.Item
          name="username"
          rules={[
            {
              type: 'string',
              required: true,
              message: '请输入用户名'
            }
          ]}
        >
          <Input placeholder="用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              type: 'string',
              required: true,
              message: '请输入密码'

            }
          ]}
        >
          <Input type="password" placeholder="密码" />
        </Form.Item>
        <Form.Item>
          <Button block type="primary" onClick={() => submit()}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
